<template>
  <p>
    <a-space>
      <a-button type="primary" @click="handleQuery">刷新</a-button>
      <a-button type="primary" @click="onAdd">新增</a-button>
      <a-button type="primary" @click="onClickGenDaily" danger>手动生成车次信息</a-button>
    </a-space>
  </p>
  <a-table :dataSource="trains"
           :columns="columns"
           :pagination="pagination"
           @change="handleTableChange"
           :loading="loading">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a-space>
          <a-popconfirm
              title="删除后不可恢复，确认删除?"
              @confirm="onDelete(record)"
              ok-text="确认" cancel-text="取消">
            <a style="color: red">删除</a>
          </a-popconfirm>
          <a @click="onEdit(record)">编辑</a>

          <a-popconfirm
              title="生成操作可能会清空数据，是否要继续？"
              @confirm="genTrainSeatHandle(record.code)"
              ok-text="确认" cancel-text="取消">
            <a style="color: #ff6d00">生成</a>
          </a-popconfirm>
        </a-space>
      </template>
      <template v-else-if="column.dataIndex === 'type'">
        <span v-for="item in TRAIN_TYPE_ARRAY" :key="item.code">
          <span v-if="item.code === record.type">
            {{ item.desc }}
          </span>
        </span>
      </template>
    </template>
  </a-table>
  <a-modal v-model:open="visible" title="车次" @ok="handleOk"
           ok-text="确认" cancel-text="取消">
    <a-form :model="train" :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
      <a-form-item label="车次编号">
        <a-input v-model:value="train.code" :disabled="!!train.id"/>
      </a-form-item>
      <a-form-item label="车次类型">
        <a-select v-model:value="train.type">
          <a-select-option v-for="item in TRAIN_TYPE_ARRAY" :key="item.code" :value="item.code">
            {{ item.desc }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="始发站">
        <a-input v-model:value="train.start"/>
      </a-form-item>
      <a-form-item label="始发站拼音">
        <a-input v-model:value="train.startPinyin" :disabled="true"/>
      </a-form-item>
      <a-form-item label="出发时间">
        <a-time-picker v-model:value="train.startTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
      </a-form-item>
      <a-form-item label="终点站">
        <a-input v-model:value="train.end"/>
      </a-form-item>
      <a-form-item label="终点站拼音">
        <a-input v-model:value="train.endPinyin"/>
      </a-form-item>
      <a-form-item label="到站时间">
        <a-time-picker v-model:value="train.endTime" valueFormat="HH:mm:ss" placeholder="请选择时间"/>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:open="genDateVisible" title="手动生成车次信息" @ok="handleGenDateOk" ok-text="确认" cancel-text="取消">
    <a-form>
      <a-form-item label="生成日期">
        <a-date-picker v-model:value="genDateValue" valueFormat="YYYY-MM-DD" placeholder="请选择日期"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts" name="train">
import {onMounted, ref, watch} from "vue";
import {notification} from "ant-design-vue";
import {TRAIN_TYPE_ARRAY} from "@/enums/TrainType";
import {save, query, deleteById, genTrainSeat, genDaily} from "@/api/base/train";
import {QueryParams, SaveParams} from "@/api/base/train/type.ts";
import {copyObj} from "@/utils/tools.ts";
import {pinyin} from "pinyin-pro";

const columns = [
  {
    title: '车次编号',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '车次类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '始发站',
    dataIndex: 'start',
    key: 'start',
  },
  {
    title: '始发站拼音',
    dataIndex: 'startPinyin',
    key: 'startPinyin',
  },
  {
    title: '出发时间',
    dataIndex: 'startTime',
    key: 'startTime',
  },
  {
    title: '终点站',
    dataIndex: 'end',
    key: 'end',
  },
  {
    title: '终点站拼音',
    dataIndex: 'endPinyin',
    key: 'endPinyin',
  },
  {
    title: '到站时间',
    dataIndex: 'endTime',
    key: 'endTime',
  },
  {
    title: '操作',
    dataIndex: 'operation'
  }
];
const visible = ref(false);
let train = ref<SaveParams>({
  id: undefined,
  code: "",
  type: "",
  start: "",
  startPinyin: "",
  startTime: "" as any,
  end: "",
  endPinyin: "",
  endTime: "",
  createTime: "",
  updateTime: "",
});
const trains = ref([]);

// 分页的三个属性名是固定的
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 15,
});

let loading = ref(false);
const genDateVisible = ref(false);
const genDateValue = ref();

const onClickGenDaily = () =>{
  genDateValue.value = undefined;
  genDateVisible.value = true;
}

const handleGenDateOk =async () => {
  try {
    const result = await genDaily(genDateValue.value);
    if (result.success) {
      notification.success({message: "操作成功！", description: "生成车次信息成功！"});
    } else {
      notification.error({message: "操作失败！", description: result.message});
    }
  } catch (e:any) {
    notification.error({message: undefined, description: e.message});
  }
  genDateVisible.value = false;
}

watch(() => train.value.start, (value: string) => {
  if (value.length != 0) {
    train.value.startPinyin = pinyin(value, {separator: '', toneType: "none"})
  }
})


const genTrainSeatHandle = async (trainCode: string) => {
  try {
    const trainSeatRes = await genTrainSeat(trainCode);
    if (trainSeatRes.success) {
      notification.success({message: "操作成功！", description: "生成车票成功！"});
    } else {
      notification.error({message: "操作失败！", description: trainSeatRes.message});
    }
  } catch (e:any) {
    notification.error({message: undefined, description: e.message});
  }
}

const onAdd = () => {
  train.value = {code: "", end: "", endPinyin: "", endTime: "", start: "", startPinyin: "", startTime: "", type: ""};
  visible.value = true;
};

const onEdit = (record: SaveParams) => {
  train.value = copyObj(record)
  visible.value = true;
};

const onDelete = async (record: SaveParams) => {
  try {
    const result = await deleteById(record.id as number);
    if (result.success) {
      notification.success({message: "操作成功！", description: "删除成功！"});
      await handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize,
      });
    } else {
      notification.error({message: undefined, description: result.message});
    }
  } catch (e: any) {
    notification.error({message: undefined, description: e.message});
  }
};

const handleTableChange = (page: any) => {
  // console.log("看看自带的分页参数都有啥：" + JSON.stringify(page));
  pagination.value.pageSize = page.pageSize;
  handleQuery({
    pageNum: page.current,
    pageSize: page.pageSize
  });
};

const handleOk = async () => {
  try {
    const result = await save(train.value);
    if (result.success) {
      notification.success({message: "success", description: "保存成功！"});
      visible.value = false;
      await handleQuery({
        pageNum: pagination.value.current,
        pageSize: pagination.value.pageSize
      });
    } else {
      notification.error({message: "失败", description: result.message});
    }
  } catch (e: any) {
    notification.error({message: "失败", description: e.message});
  }
}

const handleQuery = async (param: QueryParams) => {
  if (!param) {
    param = {
      pageNum: 1,
      pageSize: pagination.value.pageSize
    };
  }
  loading.value = true;

  try {
    const result = await query(param);
    loading.value = false;
    if (result.success) {
      trains.value = result.data as any;
      // 设置分页控件的值
      pagination.value.current = param.pageNum as number;
      pagination.value.total = result.total;
    } else {
      notification.error({message: "失败", description: result.message});
    }
  } catch (e: any) {
    notification.error({message: "失败", description: e.message});
  }
};


onMounted(() => {
  handleQuery({
    pageNum: 1,
    pageSize: pagination.value.pageSize
  });

})
</script>
